package com.example.elm_server_api.service.impl;

import com.example.elm_server_api.service.UserService;
import com.example.elm_server_api.domain.Role;
import com.example.elm_server_api.domain.SysUser;
import com.example.elm_server_api.mapper.RoleMapper;
import com.example.elm_server_api.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 张建平
 * @createtime 2022/7/26 下午5:27
 */
@Service("userDetailsService")
@Transactional
@Slf4j
public class UserDetailsServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    SysUserMapper sysUserMapper;


    /**
     *  通过用户名从数据把用户信息查询出来
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.findByUsername(username);
        //用户不存在
        if (sysUser == null) {
            log.error("User not found in the database!");
            throw  new UsernameNotFoundException("User not found in the database.");

        } else {
            //得到用户权限集
            List<GrantedAuthority> authorities = sysUser.getRoles().stream().map(role -> {
                return new SimpleGrantedAuthority(role.getName());
            }).collect(Collectors.toList());
            return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
        }
    }


    @Override
    public SysUser saveUser(SysUser user) {
        log.info("Saving new User {} to the database!", user.getUsername());
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.sysUserMapper.insert(user);
        return this.sysUserMapper.selectByPrimaryKey(user.getId());
    }

    @Override
    public Role saveRole(Role role) {
        log.info("Saving new role {} to the database!", role.getName());
        this.roleMapper.insert(role);
        return this.roleMapper.selectByPrimaryKey(role.getId());
    }

    @Override
    public void addRoleToUser(String username, String roleName) {
        log.info("Add role {} to user {}", roleName, username);
        SysUser user = this.sysUserMapper.findByUsername(username);
        Role role = this.roleMapper.selectByName(roleName);

        this.sysUserMapper.insertRoleToUser(user, role);
        // user.getRoles().add(role);
    }

    @Override
    public SysUser getUser(String username) {
        log.info("Fetching user {}", username);
        return this.sysUserMapper.findByUsername(username);
    }

    @Override
    public List<SysUser> getUsers() {
        log.info("Fetching all users.");
        return this.sysUserMapper.selectAll();
    }
}
